<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="新闻分类" prop="newsType">
        <el-cascader
          v-model="catQueryModel"
          :options="categoryList"
          :props="{ checkStrictly: true }"
          @change="handleCatQueryChange"></el-cascader>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="跳转类型" prop="urlType">
        <el-select v-model="queryParams.urlType" placeholder="请选择跳转类型  1 站内链接  2 外链 " clearable size="small">
          <el-option
            v-for="dict in dict.type.news_url_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户端" prop="showClient">
        <el-select v-model="queryParams.showClient" placeholder="请选择展示客户端" clearable size="small">
          <el-option
            v-for="dict in dict.type.news_show_client"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="投放区域" prop="allArea">
        <el-select v-model="queryParams.allArea" placeholder="请选择投放区域类型" clearable size="small" @change="allAreaChange">
          <el-option
            v-for="dict in dict.type.news_area_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="区域选择" prop="allArea" v-if="queryParams.allArea == 0">
        <el-cascader ref="cascaderAddr"
                     :props="{ checkStrictly: true }"
                     :options="areaTreeList"
                     :value="casValue"
                     :label="casLabel"
                     clearable
                     @change="handleSelectAreaChange"></el-cascader>
      </el-form-item>
      <el-form-item label="发布时间" prop="pubTime">
        <el-date-picker clearable size="small"
                        v-model="pubTimeRange"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cms:news:forceRemove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="warning"
          plain
          icon="el-icon-refresh-left"
          @click="handleReback"
          v-hasPermi="['cms:news:reback']"
        >还原</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="缩略图" align="center" prop="thumbnail" >
        <template slot-scope="scope">
          <el-image style="width: 50px" fit="contain" :src="scope.row.thumbnail"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="新闻分类" align="center" prop="catNamePath" />
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column label="发布时间" align="center" prop="pubTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pubTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跳转类型" align="center" prop="urlType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.news_url_type" :value="scope.row.urlType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户端" align="center" prop="showClient">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.news_show_client" :value="scope.row.showClient"/>
        </template>
      </el-table-column>
      <el-table-column label="投放区域" align="center" prop="province" >
        <template slot-scope="scope">
          <span v-if="scope.row.allArea == 1">全国</span>
          <span v-else>{{scope.row.province + ' '+ scope.row.city}}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handleReback(scope.row)"
            v-hasPermi="['cms:news:reback']"
          >还原</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cms:news:forceRemove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {listNews, getNews, delNews, addNews, updateNews, forceDelNews, rebackNews} from "@/api/cms/news/news";
  import { cascadeCategory } from "@/api/cms/news/category";
  import { areaCascade} from "@/api/common/common";
  import Tinymce from '@/components/Tinymce/index'
  import defSet from '@/settings'
  import { mapGetters } from 'vuex'
  export default {
    name: "News",
    components: {
      'editor': Tinymce
    },
    dicts: ['news_show_client', 'news_url_type', 'sys_is_enable', 'news_type','news_area_type'],
    data() {
      return {
        editorOpen:false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 新闻公告表格数据
        newsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          delFlag: 1,
          title: null,
          newsType: null,
          author: null,
          pubTime: null,
          urlType: null,
          showClient: null,
          provinceCode: null,
          cityCode: null,
          allArea: null,
          appid: null,
          catId: null
        },
        imgPre: defSet.imgPre,
        imageUrl: '',
        casValue: 'value',
        casLabel: 'label',
        casModel: [],
        areaTreeList: [],//行政区划数组
        activeValue: 1,
        inactiveValue: 0,
        pubTimeRange:[],
        categoryList: [],
        catQueryModel: [],
        catModel: [],
      };
    },
    created() {
      this.getList();
      this.getAreaTree();
      this.getCascadeCategory()
    },
    methods: {
      getCascadeCategory() {
        cascadeCategory().then(response => {
          // this.categoryList = response.data;
          this.categoryList = this.handleTree(response.data, "value");
        });
      },
      getAreaTree() { // 获取省市县数据并将其分类
        areaCascade({level: 2}).then(response => {
          this.areaTreeList = response.data;
          this.loading = false;
        });
      },
      /** 查询新闻公告列表 */
      getList() {
        this.loading = true;
        let qParams = this.addPubDateRange(this.queryParams,this.pubTimeRange);
        listNews(qParams).then(response => {
          this.newsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      addPubDateRange(params, dateRange) {
        var search = params;
        search.pubTimeStart = "";
        search.pubTimeEnd = "";
        if (null != dateRange && '' != dateRange) {
          search.pubTimeStart = dateRange[0] + " 00:00:00";
          search.pubTimeEnd = dateRange[1] + " 23:59:59";
        }
        return search;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.catQueryModel = [];
        this.queryParams.catId = null;
        this.pubTimeRange = []
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.newsId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 还原按钮操作 */
      handleReback(row) {
        const newsIds = row.newsId || this.ids;
        this.$modal.confirm('是否确认还原？').then(function() {
          return rebackNews(newsIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("还原成功");
        }).catch(() => {});
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const newsIds = row.newsId || this.ids;
        this.$modal.confirm('是否确认彻底删除？').then(function() {
          return forceDelNews(newsIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },


      handleSelectAreaChange(value) { // 选中省市县数据
        let len = value.length;
        this.queryParams.provinceCode = null;
        this.queryParams.cityCode = null;
        if (len == 1){
          this.queryParams.provinceCode = value[0];
        }else if (len == 2){
          this.queryParams.provinceCode = value[0];
          this.queryParams.cityCode = value[1];
        }
      },
      wrap(val) { // 选中省市县数据
        if (val.allArea == 0){
          if (val.adLevel == 1){
            this.casModel[0] = this.form.provinceCode;
          }else if(val.adLevel == 2){
            this.casModel[0] = this.form.provinceCode;
            this.casModel[1] = this.form.cityCode;
          }
        }
        this.catModel = []
        if (val.catPath){
          this.catModel = val.catPath.split(",")
        }
      },
      /** 投放区域选择事件 */
      allAreaChange(val){
        console.log('val: ' + val )
        if (val == 1){
          this.queryParams.provinceCode = undefined;
          this.queryParams.cityCode = undefined;
        }
      },
      /** 分类级联表单查询选中事件 */
      handleCatQueryChange(value) { // 表单内选中的省市县数据
        let len = value.length;
        if (len > 0){
          this.queryParams.catId = value[len -1];
        }else{
          this.queryParams.catId = null;
        }
      },
    }
  };
</script>
<style lang="less" scoped>

.avatar-uploader {
  /deep/.el-upload {
    border: 1px dashed #df2727;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.allAreaDiv{
  display: flex;
}
.allAreaDiv .allAreaSwitch{
  flex: 1;
  max-width: 200px;
  margin-top: 5px;
}
.allAreaSwitch .allAreaCas{
  flex: 1;
}
</style>
